// pages/reservation/index.js
const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    domTop: 0,
    isDomTop: false,
    toView: '',
    listDate: null, // 暂存的
    fileList: null, // 暂存的
    listIndex: 0,
    selectFile: {
      count: 0,
      price: 0,
      list: []
    },
    isView: false,
    list: [],
    imgArr: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getList();
    this.fileList();
    this.getBanner();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let self = this;
    wx.createSelectorQuery().select('#quer').boundingClientRect(function(rect){
      console.log('rest:', rect)
      self.setData({domTop: rect.top})
    }).exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getList();
    this.fileList();
    this.getBanner();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 监听滚动 
   */
  onPageScroll: function (e) {
    if (this.data.isDomTop) {
      if (e.scrollTop < (this.data.domTop - 5)) this.setData({isDomTop: false});
    } else {
      if (e.scrollTop > (this.data.domTop - 5)) this.setData({isDomTop: true});
    }
    
  },
  // 获取banner
  getBanner() {
    let url = 'mp/banner/list';
    App.ajax(url, 'GET').then(res => {
      console.log('banner数据', res);
      if (res.status === 10000) {
        this.setData({
          imgArr: res.data
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },

  // 自定义方法
  lower(e) {
    console.log('加载更多', e)
  },
  showList(e) {
    console.log(e);
    let index = e.currentTarget.dataset.index;
    this.setData({
      listIndex: index,
      toView: 'scroll' + index
    });
  },
  keep(e) {
    let all = JSON.parse(JSON.stringify(this.data.list));
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    all[id].children[index].keep = all[id].children[index].keep ? false : true;
    this.setData({
      list: all
    })
  },
  upView(e) {
    let val = e.currentTarget.dataset.val;
    if (e.currentTarget.dataset.up) val = this.data.isView ? false : true;
    this.setData({
      isView: val
    })
  },
  closeFile() {
    let self = this;
    wx.showModal({
      title: '确定清空餐盘？',
      success: function (res) {
        if (res.confirm) {
          self.closeOrder();
        }
      }
    })
  },
  closeOrder() {
    let date = JSON.parse(JSON.stringify(this.data.list));
    for (let i = 0; i < date.length; i++) {
      if (date[i].children && date[i].children.length > 0) {
        (date[i].children).map(val => {
          delete val.number;
          return val;
        })
      }
    }
    this.setData({
      selectFile: {
        count: 0,
        price: 0,
        list: []
      },
      list: date
    })
  },
  upBotCount(e) {
    let item = e.currentTarget.dataset.item;
    let pot = e.currentTarget.dataset.pot;
    let list = JSON.parse(JSON.stringify(this.data.list));
    // 找到对应的去删除
    for (let i = 0; i < list.length; i++) {
      if (list[i].children && list[i].children.length > 0) {
        (list[i].children).forEach(val => {
          if (val.id === item.id) {
            if (pot === 'min') {
              val.number -= 1;
            } else {
              val.number += 1;
            }
          }
        })
      }
    }
    this.setData({
      list: list
    })
    this.countPrice();
  },
  min(e) {
    let all = JSON.parse(JSON.stringify(this.data.list));
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    all[id].children[index].number -= 1;
    this.setData({
      list: all
    })
    this.countPrice();
  },
  max(e) {
    let all = JSON.parse(JSON.stringify(this.data.list));
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    all[id].children[index].number += 1;
    this.setData({
      list: all
    })
    this.countPrice();
  },
  countPrice() {
    let price = 0;
    let count = 0;
    let arr = [];
    let list = this.data.list;
    for (let i = 0; i < list.length; i++) {
      if (list[i].children && list[i].children.length > 0) {
        (list[i].children).forEach(val => {
          if (val.number) arr.push(val);
        })
      }
    }
    arr.map(val => {
      console.log('计算数值', val.number, val.price)
      let prices = val.number * val.price;
      price += prices;
      count += val.number;
    })
    console.log('计算', arr, price, count)
    this.setData({
      selectFile: {
        count: count,
        price: price,
        list: arr
      }  
    })
  },
  goInfo(e) {
    let item = e.currentTarget.dataset.item;
    let param = {
      id: item.id,
      c_id: item.c_id
    };
    wx.navigateTo({
      url: '/pages/order/info/index?param=' + JSON.stringify(param),
    })
  },
  goOrder() {
    if (this.data.selectFile.list.length === 0) return false;
    let arr = [];
    let list = this.data.selectFile.list;
    for (let i = 0; i < list.length; i++) {
      let date = {
        id: list[i].id,
        quantity: list[i].number
      }
      arr.push(date);
    }
    let param = {
      dishesList: arr,
      type: 2,
      remark: ''
    };
    // 存菜品信息
    wx.setStorage({
      key:"goOrder",
      data: param
    });
    this.closeOrder();
    wx.navigateTo({
      url: '/pages/order/orderPage/index'
    })
  },
  // 合并
  setList() {
    let files = this.data.fileList;
    let dates = this.data.listDate;
    let arr = [];
    for (let i = 0; i < files.length; i++) {
      let param = {
        name: files[i].name,
        children: (dates.map(val => {
          let index = (val.types).findIndex(items => {
            return items.parent_id === files[i].uid
          })
          if (index !== -1) {
            val.number = 0;
            return val;
          }
        })).filter(val => val)
      };
      arr.push(param);
    }
    console.log('结果数据', arr);
    this.setData({
      fileList: null,
      listDate: null,
      list: arr
    })
  },
  getList() {
    let url = 'mp/dishes/list';
    App.ajax(url, 'GET', '').then(res => {
      console.log('数据', res)
      if (res.status === 10000) {
        this.setData({
          listDate: res.data
        })
        if (this.data.fileList) this.setList();
      } else {
        App.prompts(res.msg);
      }
    }).catch(err => {
      console.log(err)
    })
  },
  fileList() {
    let url = 'mp/dishes/type';
    App.ajax(url, 'GET', '').then(res => {
      console.log('数据1', res)
      if (res.status === 10000) {
        this.setData({
          fileList: res.data
        })
        if (this.data.listDate) this.setList();
      } else {
        App.prompts(res.msg);
      }
    }).catch(err => {
      console.log(err)
    })
  }
})